//
//  HJSetBirthdayController.m
//  KaiChat
//
//  Created by lx on 2023/12/19.
//

#import "HJSetBirthdayController.h"
#import "QMUIButton.h"
#import "HJCheckCell.h"
#import "HJMinePresent.h"
#import "HJUserModel.h"

@interface HJSetBirthdayController ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) QMUIButton *dismissButton;
@property (nonatomic, weak) UIPickerView *pickerView;
@property (nonatomic, strong) NSMutableArray *dayDatas;
@property (nonatomic, strong) NSMutableArray *yearDatas;
@property (nonatomic, strong) NSMutableArray *monthDatas;

@property (nonatomic, assign) NSInteger yearRow;
@property (nonatomic, assign) NSInteger monthRow;
@property (nonatomic, assign) NSInteger dayRow;

@property (nonatomic, assign) NSInteger currentYear;
@property (nonatomic, assign) NSInteger currentMonth;
@property (nonatomic, assign) NSInteger currentDay;


@end

@implementation HJSetBirthdayController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIButton *maskView = [[UIButton alloc] initWithFrame:self.view.bounds].addTo(self.view);
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [maskView addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    _maskView = maskView;
    
    CGFloat contentViewH = TabbarSafeBottomMargin + 396;
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, contentViewH);
    [contentView addRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    _contentView = contentView;
    
    UIView *titleView = [UIView addToView:contentView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    
    UILabel *titleLabel = [UILabel lableWithSuperView:titleView font:UIFontMediumMake(16) color:UIColor.tj_333333Color title:@"Birthday" textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    QMUIButton *closeButton = [QMUIButton addToView:titleView];
    [closeButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:[UIImage imageNamed:@"nav_close"] forState:UIControlStateNormal];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.height.offset(30);
        make.left.offset(15);
    }];
    
    UIView *headerView = [UIView addToView:contentView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleView.mas_bottom);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    
    UILabel *yearLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(14) color:UIColor.tj_333333Color title:@"Year" textAlignment:NSTextAlignmentCenter];
    [yearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.width.offset(KScreenWidth / 3);
        make.centerY.offset(0);
    }];
    
    UILabel *monthLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(14) color:UIColor.tj_333333Color title:@"Month" textAlignment:NSTextAlignmentCenter];
    [monthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.width.offset(KScreenWidth / 3);
        make.centerY.offset(0);
    }];
    
    UILabel *dayLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(14) color:UIColor.tj_333333Color title:@"Date" textAlignment:NSTextAlignmentCenter];
    [dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.width.offset(KScreenWidth / 3);
        make.centerY.offset(0);
    }];
    
    UIView *lineView = [UIView addToView:headerView];
    lineView.backgroundColor = UIColor.tj_separatorColor;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(1);
    }];
    
    CGFloat bottomMagrin = TabbarSafeBottomMargin + 20 + buttonHeight;
    HJStyle1Button *doneButton = [HJStyle1Button buttonWithSuperView:contentView font:UIFontMediumMake(14) color:nil title:@"Done"];
    [doneButton addTarget:self action:@selector(didClickDoneButton) forControlEvents:UIControlEventTouchUpInside];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.height.offset(buttonHeight);
        make.bottom.inset(10 + TabbarSafeBottomMargin);
    }];
    
    _pickerView = [[UIPickerView alloc] init].addTo(contentView);
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.inset(bottomMagrin);
        make.top.equalTo(headerView.mas_bottom);
    }];
    
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:currentDate];
    
    self.currentYear = [components year];
    self.currentMonth = [components month];
    self.currentDay = [components day];
    
    for (NSInteger i = 99; i >= 0; i--) {
        [self.yearDatas addObject:toString(@(self.currentYear - i))];
    }
        
    for (NSInteger i = 1; i <= 12; i++) {
        [self.monthDatas addObject:toString(@(i))];
    }
    
    NSArray *selectDatas = [self.date componentsSeparatedByString:@"-"];
    if (selectDatas.count != 3) {
        selectDatas = @[
            @(2000),
            @(01),
            @(01),
        ];
    };
    
    NSInteger selectYear = [selectDatas[0] integerValue];
    NSInteger selectMonth = [selectDatas[1] integerValue];
    NSInteger selectDay = [selectDatas[2] integerValue];
    
    NSInteger selectYearIndex = 0;
    for (int i = 0; i < self.yearDatas.count; i++) {
        if ([_yearDatas[i] integerValue] == selectYear) {
            selectYearIndex = i;
            break;
        }
    }
    
    [self.pickerView selectRow:selectYearIndex inComponent:0 animated:NO];
    [self pickerView:self.pickerView didSelectRow:selectYearIndex inComponent:0];
    
    [self.pickerView selectRow:selectMonth - 1 inComponent:1 animated:NO];
    [self pickerView:self.pickerView didSelectRow:selectMonth - 1 inComponent:1];
    
    [self.pickerView selectRow:selectDay - 1 inComponent:2 animated:NO];
    [self pickerView:self.pickerView didSelectRow:selectDay - 1 inComponent:2];
}


- (NSMutableArray *)yearDatas {
    if (!_yearDatas) {
        _yearDatas = [NSMutableArray array];
    }
    return _yearDatas;
}

- (NSMutableArray *)monthDatas {
    if (!_monthDatas) {
        _monthDatas = [NSMutableArray array];
    }
    return _monthDatas;
}

- (NSMutableArray *)dayDatas {
    if (!_dayDatas) {
        _dayDatas = [NSMutableArray array];
    }
    return _dayDatas;
}

- (void)didClickDismissButton {
    [self dismissComplete:nil];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}
//这里处理了
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.yearDatas.count;
    };
    
    if (component == 1) {
        NSInteger selectYear = [self.yearDatas[_yearRow] integerValue];
        NSLog(@"selectYear = %ld", selectYear);
        if (selectYear == _currentYear) {
            return _currentMonth;
        }
        return self.monthDatas.count;
    };
    return self.dayDatas.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) return CGRectGetWidth(pickerView.frame) / 3.0;
    return CGRectGetWidth(pickerView.frame) / 3.0;
}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component API_UNAVAILABLE(tvos) {
    
    if (component == 0) {
        return self.yearDatas[row];
    }
    
    if (component == 1) {
        return self.monthDatas[row];
    }
    
    return self.dayDatas[row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel *pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textColor = UIColor.tj_1A1A1AColor;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setFont:UIFontMediumMake(16)];
    }
    
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        _yearRow = row;
        
        NSInteger selectYear = [self.yearDatas[_yearRow] integerValue];
        if (selectYear == _currentYear) {
            NSInteger selectMonth = [self.monthDatas[_monthRow] integerValue];
            if (selectMonth > _currentMonth) {
                _monthRow = _currentMonth - 1;
            }
        }
        
        [pickerView reloadComponent:1];

        if (_monthRow < self.monthDatas.count) {
            [pickerView selectRow:_monthRow inComponent:1 animated:YES];
            [self pickerView:pickerView didSelectRow:_monthRow inComponent:1];
        } else {
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [self pickerView:pickerView didSelectRow:0 inComponent:1];
        }
        return;
    }
    
    if (component == 1) {
        _monthRow = row;
        
        NSInteger selectYear = [self.yearDatas[_yearRow] integerValue];
        NSInteger selectMonth = [self.monthDatas[_monthRow] integerValue];

        [self.dayDatas removeAllObjects];
        NSInteger totalDays = [self numberOfDaysInYear:selectYear month:selectMonth];
        for (NSInteger i = 1; i <= totalDays; i++) {
            if (selectYear == self.currentYear && selectMonth == self.currentMonth && i > self.currentDay) {
                continue;
            }
            [self.dayDatas addObject:toString(@(i))];
        }
        
        [pickerView reloadComponent:2];
        
        if (_dayRow < self.dayDatas.count) {
            [pickerView selectRow:_dayRow inComponent:2 animated:YES];
            [self pickerView:pickerView didSelectRow:_dayRow inComponent:2];
        } else {
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [self pickerView:pickerView didSelectRow:0 inComponent:2];
        }
        return;
    }
    
    _dayRow =  row;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.tj_y = KScreenHeight - self.contentView.tj_height;
        self.maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    } completion:^(BOOL finished) {
    }];
    
}

- (void)dismissComplete:(void (^)(void))complete {
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.contentView.tj_y = KScreenHeight;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) {
                complete();
            }
        }];
    }];
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}

- (void)didClickDoneButton {
    
    [self.view endEditing:YES];
    [HJHUD showLoadingInView:self.view];
    
    NSInteger selectYear = [self.yearDatas[_yearRow] integerValue];
    NSInteger selectMonth = [self.monthDatas[_monthRow] integerValue];
    NSInteger selectDay = [self.dayDatas[_dayRow] integerValue];
    
    
    NSString *value = [NSString stringWithFormat:@"%ld-%02ld-%02ld", selectYear, selectMonth, selectDay];
    [HJMinePresent modifyBirth:value complete:^(NSError * _Nullable error) {
        if (error) {
            [HJHUD showErrorMessage:error.localizedFailureReason];
            return;
        }
        
        [self dismissComplete:nil];
        
        
        if (self.complete) {
            self.complete(value);
        }
        
        HJUserModel *model = [HJUserModel currentAccountModel];
        model.birthday = value;
        [model bg_saveOrUpdateAsync:nil];
        [HJHUD showSucceedMessage:@"Successful operation"];
    }];
}

- (NSInteger)numberOfDaysInYear:(NSInteger)year month:(NSInteger)month {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    
    NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
    
    components.month += 1;
    NSDate *firstDayOfNextMonth = [calendar dateFromComponents:components];
    
    NSDateComponents *difference = [calendar components:NSCalendarUnitDay
                                               fromDate:firstDayOfMonth
                                                 toDate:firstDayOfNextMonth
                                                options:0];
    
    return difference.day;
}


- (void)dealloc {
    TJLog(@"%s", __func__);
}

@end


